package com.xxx.client.android.download;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xxx.client.android.CustomApplication;

/**
 * Database implementation using Android SQLite
 */
public class DatabaseImpl implements Database {

	private static final String DB_NAME = CustomApplication.TAG
			+ "_download.db";
	private static final String TABLE_FILEDOWN = "filedown";

	private Context mContext;

	public DatabaseImpl(Context context) {
		this.mContext = context;
		create();
	}

	/**
	 * Initializes database and tables
	 */
	private void create() {
		SQLiteDatabase db = mContext.openOrCreateDatabase(DB_NAME,
				Context.MODE_PRIVATE, null);

		// create tables if necessary

		db.execSQL("CREATE TABLE IF NOT EXISTS "
				+ TABLE_FILEDOWN
				+ " (id integer primary key autoincrement, downpath varchar(100), threadid INTEGER, position INTEGER)");

		db.close();
	}

	private SQLiteDatabase getDb() {
		return mContext.openOrCreateDatabase(DB_NAME, Context.MODE_PRIVATE,
				null);
	}

	@Override
	public Map<Integer, Integer> getData(String path) {
		SQLiteDatabase db = getDb();
		Cursor cursor = db.rawQuery("select threadid, position from "
				+ TABLE_FILEDOWN + " where downpath=?", new String[] { path });
		Map<Integer, Integer> data = new HashMap<Integer, Integer>();
		while (cursor.moveToNext()) {
			data.put(cursor.getInt(0), cursor.getInt(1));
		}
		cursor.close();
		db.close();
		return data;
	}

	@Override
	public void save(String path, Map<Integer, Integer> map) {
		SQLiteDatabase db = getDb();
		db.beginTransaction();
		try {
			for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
				db.execSQL("insert into " + TABLE_FILEDOWN
						+ " (downpath, threadid, position) values(?,?,?)",
						new Object[] { path, entry.getKey(), entry.getValue() });
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		db.close();
	}

	@Override
	public void update(String path, Map<Integer, Integer> map) {
		SQLiteDatabase db = getDb();
		db.beginTransaction();
		try {
			for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
				db.execSQL("update " + TABLE_FILEDOWN
						+ " set position=? where downpath=? and threadid=?",
						new Object[] { entry.getValue(), path, entry.getKey() });
			}
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		db.close();
	}

	@Override
	public void delete(String path) {
		SQLiteDatabase db = getDb();
		db.execSQL("delete from " + TABLE_FILEDOWN + " where downpath=?",
				new Object[] { path });
		db.close();
		;
	}

}
